<template>

  <div class="vxe-container">
    <div>
      <el-row>
        <BHeaderButton
          :is-add-show="false"
          :is-edit-show="false"
          :is-del-show="false"
          :is-refresh-show="true"
          :is-send-sms-show="true"
          :is-u8-show="true"
          :is-export-show="true"
          :is-back-show="true"
          :lists="options"
          :is-lookhl-show="true"
          :is-settings-show="lookSetShow"
          :is-mu-ban-show="true"
          mb-title="备件采购部导出模板"

          @onAdd="vxeAdd(-1)"
          @onSave="vxeSave"
          @onDelete="vxeDel"
          @onU8="vxeU8"
          @onGoBack="goBack"
          @onRefresh="refresh"
          @onExport="exportTableData"
          @onMuBan="getMuBan"
          @onLookhl="lookHL"
          @onSendSms="vxeSendSms"
          @selectSettings="selectSettings"
           @selectSettingsu8="selectSettingsu8" />

      </el-row>

      <br>

      <!-- 参数配置 -->
      <el-dialog
        v-el-drag-dialog
        :visible.sync="configModal"
        :close-on-click-modal="false"
        width="85%"
        class="config-dialog">
        <head-table :config-list="configList" :key-value="key" @updateConfigData="getUpdateConfigData" />
      </el-dialog>

      <!-- SQL弹窗 -->
      <el-dialog v-el-drag-dialog :visible.sync="dialogSQLModal" :append-to-body="true" title="执行结果">
        <el-form v-loading="loadingFormSQL" ref="formSQL" :rules="rulesSQL" :model="formSQL" label-width="120px">
          <el-form-item label="SQL语句" prop="gzsql">
            <el-input v-model="formSQL.gzsql" :autosize="{ minRows: 14 }" type="textarea" />
          </el-form-item>
          <el-form-item>
            <el-button :loading="loadingFormSQL" type="primary" @click="confirmSQL">确认</el-button>
            <el-button @click="dialogSQLModal = false">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>

      <!-- 查看汇率 -->
      <el-dialog v-el-drag-dialog :visible.sync="hldialog" :append-to-body="true" width="35%" title="查看汇率">
         <el-table
          :data="HlData"
          border
          style="width: 100%">
          <el-table-column
            prop="name"
            label="名称"
            width="180">
          </el-table-column>
          <el-table-column
            prop="hl"
            label="汇率"
            width="180">
          </el-table-column>
        </el-table>
      </el-dialog>

      <!-- SendMsg弹窗 -->
      <el-dialog v-el-drag-dialog :visible.sync="dialogSendMsgModal" :append-to-body="true" width="50%" title="发送信息">
        <el-tree
          ref="selectTree"
          :props="defaultProps"
          :data="sendUsrList"
          node-key="id"
          show-checkbox
          @node-click="handleNodeClick"/>

        <br>

        <!-- {{mulSendMsgSelect}} -->
        <el-form ref="formSendMsg" :rules="rulesSendMsg" :model="formSendMsg" label-width="40px">
          <el-form-item label="内容" prop="fcontent">
            <el-input v-model="formSendMsg.fcontent" :autosize="{ minRows: 5 }" type="textarea" />
          </el-form-item>
          <el-form-item>
            <el-button :loading="loadingFormSendMsg" type="primary" @click="confirmSendMsg">确认</el-button>
            <el-button @click="dialogSendMsgModal = false">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>

    </div>
    <!-- style=" border:1px solid red;width:100%" -->
    <div style=" margin-top:-20px; ">
      <div style="border:1px solid #ddd">
        <vxe-form
          ref="vxeForm"
          :data="formData"
          :rules="{
            fprodectno: [{
              required: true,
              message: '请输入项目号',
              trigger: 'blur'
            }],
            fzhibaoqi: [{
              required: true,
              message: '请选择质保期',
              trigger: 'change'
            }]
        }">
          <template v-for="item in dialogThead">
            <template v-if="item.frepfld==='fzhibaoqi'">
              <vxe-form-item
                :key="item.frepfld"
                :title="item.frepcap"
                :field="item.frepfld"
                :title-colon="true"
                title-align="right"
                title-width="80px">
                <template #default>
                  <vxe-select v-model="formData[item.frepfld]" clearable filterable style="width: 120px;" placeholder="请选择">
                    <vxe-option
                      v-for="item in fzbqList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"/>
                  </vxe-select>
                </template>
              </vxe-form-item>
            </template>
            <template v-else>
              <vxe-form-item
                :key="item.frepfld"
                :title="item.frepcap"
                :field="item.frepfld"
                :title-colon="true"
                title-align="right"
                title-width="80px">
                <template v-if="item.fisedit == 1" #default>
                  <vxe-input v-model="formData[item.frepfld]" placeholder="请输入" clearable disabled />
                </template>
                <template v-else #default>
                  <vxe-input v-model="formData[item.frepfld]" placeholder="请输入" clearable />
                </template>
              </vxe-form-item>
            </template>
          </template>

        </vxe-form>
      </div>



      <vxe-grid
        ref="xGrid"
        v-bind="gridOptions"
        :seq-config="{ startIndex: (tablePage.currentPage - 1) * tablePage.pageSize }"
        :footer-cell-class-name="footerCellClassName"
        @edit-closed="cellClosed"
        @toolbar-button-click="toolbarButtonClickEvent">

        <template #fwaibi_default="{ row }">
          <span>{{ formatField(row.fwaibi) }}</span>
        </template>
        <template #fwaibi_edit="{ row, column }">
          <vxe-select v-model="row.fwaibi" transfer @change="selectChangeEvent({ row, column })">
            <vxe-option v-for="item in fwaibiList" :key="item.value" :value="item.value" :label="item.label"/>
          </vxe-select>
        </template>
        <template #toolbar_buttons />

        <!-- <template #pager>
          <vxe-pager
            :layouts="['Sizes', 'PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'FullJump', 'Total']"
            :current-page.sync="tablePage.currentPage"
            :page-size.sync="tablePage.pageSize"
            :total="tablePage.total"
            @page-change="handlePageChange" />
        </template> -->
      </vxe-grid>
    </div>



     <!-- 导入 -->
     <el-dialog
      v-el-drag-dialog
      :title="importGrid.title"
      :visible.sync="importGrid.fmodal"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :before-close="handleClose"
      :show-close="true"
      class="import-set-modal"
      width="95%"
      @close="closeImportDialog">
      <div class="search-grid" style="margin-bottom: 20px;">
        <vxe-button status="success" icon="vxe-icon-save" content="保存" @click="importGridSave"/>
        <vxe-button class="import-excel" status="primary" content="导入Excel" @click="toImport" />
        <vxe-button status="success" icon="vxe-icon-delete" content="删除" @click="importGridDel"/>
        <ExcelImport
          :ref="importGrid.excelRefs"
          :data-row="importGrid.dataRow"
          :value-match="importGrid.fieldArr"
          :accept="importGrid.accept"
          @changeExcel="uploadExamFile" />
      </div>
      
      <vxe-grid
        :class="importGrid.class"
        :id="importGrid.id"
        :ref="importGrid.gridRefs"
        :print-config="{}"
        :import-config="{}"
        :export-config="{}"
        :columns="importGrid.columns"
        :toolbar-config="importGrid.tableToolbar"
        :data="importGrid.data"
        :custom-config="{storage: true}"
        :edit-config="{trigger: 'click', mode: 'row', showStatus: true}"
        align="center"
        height="450"
        border
        resizable
        keep-source>
    
        <template #fqtykykc_edit="{row}">
          <vxe-input v-model="row.fqtykykc" />
        </template>

        <template #fwaibi_edit="{row}">
          <vxe-input v-model="row.fwaibi" />
        </template>

        <template #fcaigouybprice_edit="{row}">
          <vxe-input v-model="row.fcaigouybprice" />
        </template>
        <template #fremark_edit="{row}">
          <vxe-input v-model="row.fremark" />
        </template>
        
      </vxe-grid>
    </el-dialog>




  </div>

</template>
<script>
let FRepKey = ''
// let opername = ''
let fbillno = ''

import XEUtils from 'xe-utils'
import VXETable from 'vxe-table'
import 'vxe-table/lib/style.css'
import { vxetableBillConfig, vxetableGenAdd, tableConfig, apiSql, apiFileSave, XsbList, getDanHao, beijianSave, beijianEdit, admin } from '../../api/account'
import { checkStatus, getCSData } from '../../api/salary'
import { sendsms, beijianTree, getU8,beijianCGImport } from '../../api/peijian'
import { download } from '../../mixins/download.js'
import { common } from '../../mixins/common'
import VXETablePluginShortcutKey from 'vxe-table-plugin-shortcut-key'
import '../../styles/vxetable.scss'
import HeadTable from '../salary/headTable/Billindex.vue'

VXETable.use(VXETablePluginShortcutKey, {
  // 功能键设置
  setting: {
    'table.edit.tab.rightMove': 'Enter',
    'table.edit.tab.leftMove': 'shift + Tab'

  }
})

export default {
  components: {
    HeadTable
  },
  mixins: [download, common],
  data() {
    return {
      hldialog:false,
      HlData:[],
      u8:-1,
      importGrid: {
        class: 'import-set-modal',
        rows: '',
        fmodel: '',
        fbrand: '',
        title: '备件采购（导入）',
        excelRefs: 'importExcel', // ExcelImport
        isFormData: true,
        dataRow: 0, // 数据开始行 默认从第0行开始
        fieldCap: [
          { field: 'fbillno',width:110,fisedit:0, frecap: '流水号' },
          { field: 'fprodectno',width:100,fisedit:0, frecap: '项目号' },

          { field: 'fbeijianname', width:100,fisedit:0, frecap: '备件名称' },
          { field: 'fbeijiancode',width:100,fisedit:0,  frecap: '备件代码' },
          { field: 'fbeijianhao',width:120, fisedit:0, frecap: '物料号 ' },
          { field: 'ftuhao',width:60,fisedit:0,  frecap: '图号' },
          { field: 'fid',width:60, fisedit:0, frecap: '内码' },
          { field: 'funit',width:60, fisedit:0, frecap: '单位' },
          { field: 'fqtyxq',width:80, fisedit:0, frecap: '需求数量' },

          { field: 'fqtykc', width:80,fisedit:0, frecap: '库存数量' },
          { field: 'fkucunprice',width:100, fisedit:0, frecap: '库存单价不含税' },
          { field: 'fcaigouprice', width:100,fisedit:0, frecap: '最近的采购单价不含税' },
          { field: 'fqtykykc',width:100, fisedit:1, frecap: '可用的库存数量' },
          { field: 'fwaibi', width:100,fisedit:1,  frecap: '采购币种' },
          { field: 'fcaigouybprice', width:100,fisedit:1, frecap: '现在采购的采购原币单价' },
          { field: 'fcaigourmbprice', width:100,fisedit:0, frecap: '现在买需要的采购人民币单价' },
          { field: 'fcaigouamount', width:100,fisedit:0, frecap: '现在的采购总价' },
          { field: 'fqihuo',width:60,fisedit:0,  frecap: '货期' },

          { field: 'fremark', width:100,fisedit:1, frecap: '备注' }
          // { field: 'fqtykc', frecap: '库存数量' },
          // { field: 'fqtykykc', frecap: '可用的库存数量' },
          // { field: 'fcbprice', frecap: '成本单价' },
          // { field: 'fcbamount', frecap: '成本总价' }
        ],
        fieldArr: [], // 数据列 必须与excel中的表列顺序相对应
        valueTitle: [], // frecap
        accept: '.xls,.xlsx',
        id: 'import-grid',
        gridRefs: 'importTable', // vxe-grid
        fmodal: false,
        data: [],
        columns: [
          { type: 'checkbox', width: 50 },
          { type: 'seq', width: 60 }
        ],
        formData: {
          fbillno: '', // 流水号
          fchuanmin: '', // 船名
          fchuanhao: '', // 船号
          fmodel: '', // 机型
          fprodectno: '', // 项目号
          fcustomer: '', // 客户
          fzhibaoqi: '' // 质保期
        }
      },




      fqtykc: [],
      formData: {

      },
      dialogThead: [],
      columnHeaderData: [],
      columnData: [],
      opername: '',
      aaValue: '',
      oriColumnData: [],

      configList: [],
      configModal: false,
      menusList: [],
      limits: [],
      options: [],
      lookSetShow: false,
      key: 0,
      dialogSQLModal: false,
      loadingFormSQL: false,
      formSQL: {
        gzsql: ''
      },
      rulesSQL: {
      },

      dialogSendMsgModal: false,
      loadingFormSendMsg: false,
      userList: [],
      sendUsrList: [],
      formSendMsg: {

      },
      rulesSendMsg: {

      },
      // mulSendMsgSelect: [],
      // pagesizes: [20, 50, 100, 300, 500],
      defaultProps: {
        children: 'children',
        label: 'label'
      },

      tablePage: {
        total: 0,
        currentPage: 1,
        pageSize: 20
      },
      vxeDisabled: false,

      keyword: '',
      isHebing: '0',
      gridOptions: {
        border: true,
        showHeaderOverflow: true,
        showOverflow: true,
        showFooterOverflow: true,
        keepSource: true,
        autoResize: true,
        resizable: true,

        // height: this.heightGD(),
        showFooter: true,
        round: true,
        size: 'mini',

        id: 'full_edit_1',
        rowId: 'id',
        rowConfig: {
          isHover: true,
          isCurrent: true
        },
        // columnConfig: {
        //   resizable: true
        // },

        // 自定义列配置项
        customConfig: {
          storage: true,
          checkMethod: this.checkColumnMethod
        },

        keyboardConfig: {
          isEnter: true,
          isArrow: true
        },
        editRules: {
          fzhibaoqi: [
            { required: true, message: '必须填写' }
          ] },
        // formConfig: {
        //   titleWidth: 100,
        //   titleAlign: 'right',
        //   items: [
        //     // { field: 'name', title: '名称', span: 8, titlePrefix: { message: 'app.body.valid.rName', icon: 'vxe-icon-info-circle-fill' }, itemRender: { name: '$input', props: { placeholder: '请输入名称' }}},
        //     // { field: 'email', title: '邮件', span: 8, titlePrefix: { useHTML: true, message: '点击链接：<a class="link" href="https://vxetable.cn" target="_blank">vxe-table官网</a>', icon: 'vxe-icon-question-circle-fill' }, itemRender: { name: '$input', props: { placeholder: '请输入邮件' }}},
        //     // { field: 'nickname', title: '昵称', span: 8, itemRender: { name: '$input', props: { placeholder: '请输入昵称' }}}
        //     // { field: 'role', title: '角色', span: 8, folding: true, itemRender: { name: '$input', props: { placeholder: '请输入角色' }}},
        //     // { field: 'sex', title: '性别', span: 8, folding: true, titleSuffix: { message: '注意，必填信息！', icon: 'vxe-icon-info-circle-fill' }, itemRender: { name: '$select', options: [] }},
        //     // { field: 'age', title: '年龄', span: 8, folding: true, itemRender: { name: '$input', props: { type: 'number', min: 1, max: 120, placeholder: '请输入年龄' }}}
        //     // { span: 24, align: 'center', collapseNode: true, itemRender: { name: '$buttons', children: [{ props: { type: 'submit', content: '搜索', status: 'primary' }}, { props: { type: 'reset', content: '重置' }}] }}
        //   ]
        // },

        toolbarConfig: {
          // custom: true,
          buttons: [
            // { code: 'myInsert', name: '新增', icon: 'vxe-icon-square-plus', status: 'success' },
            // { code: 'myDelete', name: '删除', icon: 'vxe-icon-delete', status: 'success' },
            // { code: 'mySave', name: '保存', icon: 'vxe-icon-save', status: 'success' }
            // { code: 'myInsertTZ', name: '新增跳转', icon: 'vxe-icon-square-plus', status: 'success' }
            // { code: 'myOper', name: '操作', icon: 'vxe-icon-square-down', status: 'success', slots: 'default', dropdowns: [{ code: 'myAA', 'name': 'AA', status: 'info', icon: 'vxe-icon-square-plus-fill' }, { code: 'myBB', 'name': 'BB', status: 'info', icon: 'vxe-icon-square-plus-fill' }] }
          ],
          slots: {
            buttons: 'toolbar_buttons'
          }

        },
        columns: [],
        data: [],

        checkboxConfig: {
          // labelField: 'id',
          reserve: true,
          highlight: true,
          range: true
        },

        editConfig: {
          trigger: 'click',
          mode: 'cell',
          showStatus: true, // 是否显示单元格新增与修改状态
          showIcon: false // 是否显示列头编辑图标
          // activeMethod: this.activeRowMethod
        }

      },
      fzbqList: [
        { label: '0月', value: '0月' },
        { label: '1月', value: '1月' },
        { label: '2月', value: '2月' },
        { label: '3月', value: '3月' },
        { label: '4月', value: '4月' },
        { label: '5月', value: '5月' },
        { label: '6月', value: '6月' },
        { label: '7月', value: '7月' },
        { label: '8月', value: '8月' },
        { label: '9月', value: '9月' },
        { label: '10月', value: '10月' },
        { label: '11月', value: '11月' },
        { label: '12月', value: '12月' }

      ],
      fwaibiList: [
        { label: '人民币', value: '人民币' },
        { label: '美元', value: '美元' },
        { label: '欧元', value: '欧元' },
        { label: '日元', value: '日元' },
        { label: '英镑', value: '英镑' },
        { label: '瑞士法郎', value: '瑞士法郎' }
      ],
      fsetffax: 0,
      hv: {
        fsethuilv: 0,
        fsethuilvfalang: 0,
        fsethuilvoyuan: 0,
        fsethuilvriyuan: 0,
        fsethuilvyingpang: 0
      }
    }
  },
  Mounted: {

  },
  computed: {

  },
  async created() {
 
    FRepKey = this.$route.query.key
    fbillno = this.$route.query.fbillno
    // 这里有fid -- 修改
    // opername = decodeURIComponent(this.globalDb.fname)
    this.opername = decodeURIComponent(this.globalDb.fname)

    // await this.getAdmin()

    await this.getvxetableBillConfig() 
    if (fbillno) {
      await this.getBeijianEdit()
      const $grid = this.$refs.xGrid
      setTimeout(() => {
        const { tableData } = $grid.getTableData()
        for (let index = 0; index < tableData.length; index++) {
          const id = tableData[0].id
          const fqtykc = tableData[0].fqtykc
          this.fqtykc[index] = {
            'id': id,
            'fqtykc': fqtykc
          }
        }
      }, 0)
    
    } else {
      await this.getvxetableGenList()
      const $grid = this.$refs.xGrid
      for (let i = 0; i < 1; i++) {
        setTimeout(() => {
          $grid.insertAt(-1, -1)
        }, 0)
      }
    }

    await this.getColumns()

    this.lookSetShow = JSON.parse(localStorage.getItem('flookSet'))

    // 菜单列表（权限）
    // const menuRes = JSON.parse(localStorage.getItem('setMenuData'))
    // console.log(11111, menuRes, FRepKey )
    // this.menusList = menuRes
    // if (menuRes.length >= 1) {
    //   menuRes.map(it => {
    //     it.children.map(item => {
    //       if (item.fobjectid ==parseInt(FRepKey)) {
    //         this.$set(this, 'limits', item.child)
    //       }
    //     })
    //   })
    // }

    // 参数
    this.getCSData()

    // 参数设置
    const setConfigData = JSON.parse(localStorage.getItem('setConfigData'))
    // this.$set(this, 'setConfigData', setConfigData)

    this.fsetffax = Number(setConfigData.fsetffax)

    this.hv.fsethuilv = Number(setConfigData.fsethuilv) // 美元
    this.hv.fsethuilvfalang = Number(setConfigData.fsethuilvfalang) // 瑞士法郎
    this.hv.fsethuilvoyuan = Number(setConfigData.fsethuilvoyuan)// 欧元
    this.hv.fsethuilvriyuan = Number(setConfigData.fsethuilvriyuan)// 日元
    this.hv.fsethuilvyingpang = Number(setConfigData.fsethuilvyingpang)// 英镑

  },
  methods: {
    async getCSData() {
      try {
        // FSetLoginName
        const res = await getCSData({ opername: decodeURIComponent(this.globalDb.fname), fcategory: 'IB', fkey: '', db: this.globalDb.db })
        if (res.Data) {
          this.loginTitleName = res.Data.fsetloginname
          localStorage.setItem('setConfigData', JSON.stringify(res.Data))
        }
      } catch (error) {
        console.log(error)
      }
    },
    activeRowMethod({ row, column, columnIndex }) {
      console.log(10000, row, column, columnIndex)
    },

    editDisabledEvent({ row }) { },

    editClosedEvent({ row }) { },

    // // 高度
    // heightGD() {
    //   return (document.body.offsetHeight - 185) + 'px'
    // },
    selectSettings(val) {
      if (val === 0) {
        this.settings()
      } else if (val === 1) {
        this.dialogSQL()
      }
    },
    selectSettingsu8(val) {
       this.u8 = val
       this.vxeU8 ()
    },

    settings() {
      this.configModal = true
      this.getTableConfig()
    },
    async getTableConfig() {
      try {
        this.configLoading = true
        const res = await tableConfig({
          db: this.globalDb.db,
          opername: this.opername,
          key: FRepKey,
          billtype: 1
        })
        this.configList = res.Data
        this.key = FRepKey
        this.configLoading = false
      } catch (error) {
        this.configLoading = false
      }
    },

    // SQL修改/更新
    async dialogSQL() {
      this.dialogSQLModal = true
      try {
        const res = await apiSql({
          db: this.globalDb.db,
          opername: this.opername,
          type: 1,
          FRepKey
        })

        if (res.Error === 0) {
          this.formSQL.gzsql = res.Data
          this.formSQL.FRepKey = FRepKey
        }
        setTimeout(() => {
          this.$refs['formSQL'].clearValidate()
        })
      } catch (error) {
        // console.log(error)
      }
    },

    confirmSQL() {
      this.$refs['formSQL'].validate(async(valid) => {
        if (valid) {
          try {
            this.formSQL.db = this.globalDb.db
            this.formSQL.opername = this.opername
            this.formSQL.type = 1
            const res = await apiFileSave(this.formSQL)
            if (res.Error === 0) {
              this.dialogSQLModal = false
              this.$message({
                message: res.Message,
                type: 'success'
              })
            } else {
              this.$message({
                message: res.Message,
                type: 'error'
              })
            }
          } catch (error) {
            // console.log(error)
          }
        } else {
          return false
        }
      })
    },
    calculatePrice(row, column, fsetffax, hv) {
      // 原币
      // 现在采购的采购原币单价(fcaigouybprice) = 现在买需要的采购人民币单价(fcaigourmbprice)
      // 现在的采购总价(fcaigouamount)   = 需求数量(fqtyxq) * 现在买需要的采购人民币单价(fcaigourmbprice)
      if (column.field === 'fcaigouybprice' || column.field === 'fwaibi') { // 现在采购的采购原币单价
        const fcaigourmbprice = Number(row.fcaigouybprice) * hv * (1 + fsetffax / 100)
        const fcaigouamount = Number(row.fqtyxq) * fcaigourmbprice
        this.gridOptions.data.map(it => {
          if (it.fid === row.fid) {
            this.$set(it, 'fcaigourmbprice', fcaigourmbprice.toFixed(2))
            this.$set(it, 'fcaigouamount', fcaigouamount.toFixed(2))
          }
        })
      }

     
    },
    cellClosed({ row, rowIndex, $rowIndex, column, columnIndex, $columnIndex }) {
      switch (row.fwaibi) {
        case '人民币':
          this.calculatePrice(row, column, 0, 1)
          break
        case '美元':
          this.calculatePrice(row, column, this.fsetffax, this.hv.fsethuilv * 1.06)
          break
        case '欧元':
          this.calculatePrice(row, column, this.fsetffax, this.hv.fsethuilvoyuan * 1.06)
          break
        case '日元':
          this.calculatePrice(row, column, this.fsetffax, this.hv.fsethuilvriyuan * 1.06)
          break
        case '英镑':
          this.calculatePrice(row, column, this.fsetffax, this.hv.fsethuilvyingpang * 1.06)
          break
        case '瑞士法郎':
          this.calculatePrice(row, column, this.fsetffax, this.hv.fsethuilvfalang * 1.06)
          break
          // fqtykc 库存数量
          // fqtykykc 可用的库存数量
          // 可用库存数量小于0，用现在买需要的采购人民币单价*（1+利润率）；可用库存数量大于0，用（库存单价与最近的采购单价较高*1.13*可用库存数量+（需求数据-可用库存数量）*现在买需要的采购人民币单价）*（1+利润率）
      }
 
      if (column.field === 'fqtykykc') { //  可用的库存数量
        // console.log(this.gridOptions.data, ' this.gridOptions')
        this.gridOptions.data.map(it => {
          if (it.fid === row.fid) {
            if (Number(row.fqtykc) <= Number(row.fqtykykc)) {
              this.$set(it, 'fqtykykc', row.fqtykc)
            } else {
              this.$set(it, 'fqtykykc', row.fqtykykc)
            }
          }
        })
      }

    },
    selectChangeEvent({ row, column }) {

    },
    formatField(value) {
      if (value) {
        return value
      }
    },
    // 更新数据
    async getUpdateConfigData() {
      await this.getTableConfig()
    },

    // 添加表格背景颜色
    footerCellClassName({ $rowIndex, columnIndex }) {
      // if (columnIndex === 0) {
      if ($rowIndex === 0) {
        // return 'col-blue'
        // }
      }
    },

    // 字段
    async getvxetableBillConfig() {
      const res = await vxetableBillConfig(
        {
          FUnControl: -1,
          opername: this.opername,
          FRepKey,
          FRepPage: 1

        }
      )
      this.oriColumnData = res.Data
      const dataVxe = []
      // setTimeout(() => {
      if (res.Data.length > 0) {
        this.columnData.push({
          type: 'seq',
          width: 50,
          fixed: 'left'
        })
        // this.columnData.push({
        //   type: 'checkbox',
        //   width: 50,
        //   fixed: 'left'
        // })

        for (let i = 0; i < res.Data.length; i++) {
          // FRepType 202, 200 -- 文本， 131 --数值 ，135 -- 日期
          if (res.Data[i].fheaderfooter === 1) {
            // 表体字段
            if (res.Data[i].falign === 1) {
              this.columnData.push({
                field: res.Data[i].frepfld,
                title: res.Data[i].frepcap,

                headerAlign: 'left',
                align: 'right',

                width: res.Data[i].frepwid > 0 ? res.Data[i].frepwid : 0,
                editRender: { name: 'input', attrs: { disabled: Boolean(res.Data[i].fisedit), placeholder: '' }}
              })
            } else if (res.Data[i].frepmeg === 1) {
              if (res.Data[i].frepfld === 'funit') {
                this.columnData.push({
                  field: res.Data[i].frepfld,
                  title: res.Data[i].frepcap,
                  headerAlign: 'left',
                  align: 'right',
                  width: res.Data[i].frepwid > 0 ? res.Data[i].frepwid : 0,
                  editRender: { name: '$select', enabled: !res.Data[i].fisedit, options: [
                    {
                      label: '台',
                      value: '台'
                    },
                    {
                      label: '个',
                      value: '个'
                    },
                    {
                      label: '件',
                      value: '件'
                    }
                  ], placeholder: '请选择' }
                })
              }
            } else {
              const frepfld = res.Data[i].frepfld
              const isFrepfld = frepfld === 'fwaibi' // 采购币种
              if (isFrepfld) {
                // console.log(res.Data[i].frepfld, ' res.Data[i].frepfld')
                this.columnData.push({
                  field: res.Data[i].frepfld,
                  title: res.Data[i].frepcap,

                  headerAlign: 'left',
                  align: 'right',

                  width: res.Data[i].frepwid > 0 ? res.Data[i].frepwid : 0,
                  slots: {
                    default: res.Data[i].frepfld + '_default',
                    edit: res.Data[i].frepfld + '_edit'
                  },
                  editRender: { name: 'option', attrs: { disabled: Boolean(res.Data[i].fisedit) }}
                })
              } else {
                if (res.Data[i].frepfld === 'fqtykykc') {
                  this.columnData.push({
                    field: res.Data[i].frepfld,
                    title: res.Data[i].frepcap,
                    // showHeaderOverflow: true,
                    // showOverflow: true,
                    // resizable: true,
                    width: res.Data[i].frepwid > 0 ? res.Data[i].frepwid : 0,
                    formatter({ cellValue }) {
                      console.log(cellValue, ' cellValue')
                      return cellValue ? `${XEUtils.commafy(Number(cellValue), { digits: 0 })}` : 0
                    },
                    editRender: {
                      name: 'input',
                      attrs: { disabled: Boolean(res.Data[i].fisedit), placeholder: '' },
                      props: { type: 'float', digits: res.Data[i].fdecplaces, min: 0, step: 10, placeholder: '请输入数值' }
                    }
                  })
                } else if (
                  res.Data[i].frepfld === 'fbeijianname' ||
                  res.Data[i].frepfld === 'fbeijiancode' ||
                  res.Data[i].frepfld === 'fbeijianhao'
                ) {
                  this.columnData.push({
                    field: res.Data[i].frepfld,
                    title: res.Data[i].frepcap,
                    fixed: 'left',
                    headerAlign: 'left',
                    align: 'right',

                    width: res.Data[i].frepwid > 0 ? res.Data[i].frepwid : 0,
                    editRender: { name: 'input', attrs: { disabled: Boolean(res.Data[i].fisedit), placeholder: '' }}
                  })
                } else {
                  // (({ cellValue, row, column }) =&gt; string) | any[] | string
                  // console.log(res.Data[i].frepfld, ' res.Data[i].frepfld ', res.Data[i].frepcap)
                  this.columnData.push({
                    field: res.Data[i].frepfld,
                    title: res.Data[i].frepcap,
                    // showHeaderOverflow: true,
                    // showOverflow: true,
                    // resizable: true,
                    width: res.Data[i].frepwid > 0 ? res.Data[i].frepwid : 0,
                    formatter({ cellValue, row, column }) {
                      // console.log(cellValue, ' cellValue')
                      // console.log(row, ' row')
                      // console.log(column, ' column')
                      if (
                        column.property === 'fqtyxq' || // 需求数量
                        column.property === 'fqtykc' // 库存数量
                      ) {
                        return cellValue ? `${XEUtils.commafy(Number(cellValue), { digits: 0 })}` : 0
                      } else if (
                        column.property === 'fkucunprice' || // 库存单价不含税
                        column.property === 'fcaigouprice' || // 最近的采购单价不含税
                        column.property === 'fcaigouybprice' || // 现在采购的采购原币单价
                        column.property === 'fcaigourmbprice' || // 现在买需要的采购人民币单价
                        column.property === 'fcaigouamount' // 现在的采购总价
                      ) {
                        return cellValue ? `${XEUtils.commafy(Number(cellValue), { digits: 2 })}` : 0
                      } else {
                        return cellValue
                      }
                    },
                    editRender: {
                      name: 'input',
                      attrs: { disabled: Boolean(res.Data[i].fisedit), placeholder: '' },
                      props: { type: 'float', digits: res.Data[i].fdecplaces, min: 0, step: 10, placeholder: '请输入数值' }
                    }
                  })
                }
              }
            }
          } else {
            // 表头
            this.dialogThead.push(res.Data[i])
            // columnHeaderData
            this.columnHeaderData.push({
              field: res.Data[i].frepfld,
              title: res.Data[i].frepcap,
              // showHeaderOverflow: true,
              // showOverflow: true,
              // resizable: true,
              titleColon: true,
              titleWidth: res.Data[i].frepwid > 0 ? res.Data[i].frepwid : 0

            })
 
          }
        }
     

        this.dialogThead.map(item => { dataVxe[item.frepfld] = '' })
        for (const i in dataVxe) {
          this.$set(this.formData, i, dataVxe[i])
        }

        this.gridOptions.columns = this.columnData
      }
    },
    async vxeU8() {
      // VXETable.modal.message({ content: ` 同步获取数据需到现在调试。。。`, status: 'warning' })
      // return
      const res = await getU8({
        opername: decodeURIComponent(this.globalDb.fname),
        fbillno: this.formData.fbillno,
        FRepKey,
        u8:this.u8
      })
      this.u8=-1
      if (res.Error === 0) {
        this.$message({
          message: '同步成功',
          type: 'success'
        })
        this.gridOptions.data = res.Data
 
      } else {
        this.$message({
          message: '失败',
          type: 'error'
        })
      }
    },

    //
    async vxeSendSms() {
      this.dialogSendMsgModal = true
      await this.getBeijianTree()
    },
    handleNodeClick(data) {
      console.log(data)
    },
    async confirmSendMsg() {
      const selectMsgArr = this.$refs.selectTree.getCheckedKeys(true)
      this.dialogSendMsgModal = true
      try {
        const fcontent = this.formSendMsg.fcontent
        const fbillno = this.formData.fbillno
        if (selectMsgArr.length) {
          const fid = selectMsgArr.join(',')
          if (!fid) {
            this.$message({
              message: '手机号为空',
              type: 'error'
            })
            return
          }

          const res = await sendsms({
            opername: decodeURIComponent(this.globalDb.fname),
            fid,
            fcontent,
            fbillno
          })
          console.log(res, ' res')
          if (res.Error === 0) {
            this.mulSendMsgSelect = []
            this.formSendMsg.fcontent = ''
            this.dialogSendMsgModal = false
          }
        } else {
          this.$message({
            message: '未选中发送信息通知人员',
            type: 'error'
          })
          return
        }
      } catch (error) {
        this.dialogSendMsgModal = false
      }
    },
    async getBeijianTree() {
      try {
        this.sendMsgLoading = true
        const res = await beijianTree({
          opername: decodeURIComponent(this.globalDb.fname)
        })
        console.log(res, ' res')

        this.sendUsrList = res.Data
        this.sendMsgLoading = false
      } catch (error) {
        this.sendMsgLoading = false
        console.log(error)
      }
    },
    async getAdmin() {
      try {
        this.sendMsgLoading = true
        const res = await admin({
          db: this.globalDb.db,
          opername: this.loginname,
          keyword: this.keyword,
          username: this.loginname,
          limit: this.pagesize,
          page: this.currentPage
        })
        this.userList = res.result
      } catch (error) {
        console.log(error)
      }
    },
    //查看汇率
     lookHL(){
      this.hldialog=true
      this.HlData =[{'name':'美元','hl':this.hv.fsethuilv},{'name':'欧元','hl':this.hv.fsethuilvoyuan},{'name':'日元','hl':this.hv.fsethuilvriyuan},{'name':'英镑','hl':this.hv.fsethuilvyingpang},{'name':'瑞士法郎','hl':this.hv.fsethuilvfalang}];
     },
     handleClose(){
      window.location.reload()
     },

    // 刷新
    refresh() {
      window.location.reload()
    },

    //导入
    async  exportTableData() {
      const type = await VXETable.modal.confirm("1、导入之前先同步U8 \n 2、请先导出备件采购部导出模板数据，只需填写 可用的库存数量、采购币种、现在采购的采购原币单价")
      if( type === "confirm"){
        this.importGrid.fmodal = true
        this.importGridDel()
       // this.$set(this.importGrid.formData, 'fbillno', this.formData.fbillno)
      }
    },

    importGridDel() { // 删除当前行
      const $grid = this.$refs[this.importGrid.gridRefs]
      if ($grid) {
        const checkData = $grid.getCheckboxRecords()
        if (checkData.length) {
          $grid.removeCheckboxRow()
        } else {
          this.importGrid.data = []
          $grid.remove($grid.getCheckboxRecords())
        }
      }
   
    },
    toImport() {
      this.$refs[this.importGrid.excelRefs].open()
    },
    async importGridSave() { // 导入保存
      const $grid = this.$refs[this.importGrid.gridRefs]
      $grid.getRecordset()
      const { fullData } = $grid.getTableData()
      try {
        const res = await beijianCGImport({
          FRepKey,
          opername: this.opername,
          data: fullData
        })
        if (res.Error === 0) {
          this.$message({
            message: res.Message,
            type: 'success'
          })
        
        } else {
          this.$message({
            message: res.Message,
            type: 'error'
          })
        }
      } catch (error) {
        console.log(error)
      }
    },
     // 获取数据
     uploadExamFile(data) {   
      const dataArr = data
      this.importGrid.data = dataArr
    },
    closeImportDialog() {
      this.importGrid.rows = ''
      this.importGrid.fbillno = ''
      this.importGrid.fmodel = ''
      this.importGrid.fbrand = ''
      this.importGridDel()
    },

    getColumns() {
      this.importGrid.fieldCap.map(item => {
        this.importGrid.fieldArr.push(item.field)
        this.importGrid.valueTitle.push(item.frecap)
        if( item.fisedit == 1){
          this.importGrid.columns.push({
            field: item.field,
            title: item.frecap,
            width: item.width,
            editRender: {},
            slots: { edit: item.field + '_edit' }
          })
        }else{
          this.importGrid.columns.push({
            field: item.field,
            title: item.frecap,
            width: item.width,
            
            
          })
        }
      })
    },


 

    //导出
  async  getMuBan() {
      this.headerKeys = []
      this.header = []
      this.listData = []
      const listData =  this.gridOptions.data 
      this.columnData .filter((item,index) => {
          if (index !== 0  && !item.frephide) {
            this.header.push(item.title)
            this.headerKeys.push(item.field)
          }
        })
        //项目号 //流水号
        this.header.unshift("项目号");
        this.header.unshift("流水号");
        this.headerKeys.unshift("fprodectno");
        this.headerKeys.unshift("fbillno");

        this.filename = "备件报价"+this.formData.fbillno 
        listData.map((item, index) => {
            this.listData[index] = {}
            this.headerKeys.map(it => {
              this.listData[index][it] = item[it]
            })
          })
       await this.exportData()
    },

    // 新增
    vxeAdd(row) {
      console.log(row, 'row')
      const $grid = this.$refs.xGrid
      $grid.insertAt(row, -1)
      // const total = 50
      // for (var i = 0; i <= total; i++) {
      //   $grid.insert({})
      // }
    },
    goBack() {
      this.$router.push('/peijian/pjbjcg')
    },
    // 保存
    async vxeSave() {
      const $grid = this.$refs.xGrid
      const { insertRecords, removeRecords, updateRecords } = $grid.getRecordset()
      const { tableData } = $grid.getTableData()
      // console.log(insertRecords, removeRecords, updateRecords, 111111, this.formData)
      // if (insertRecords.length === 0 && updateRecords.length === 0 && removeRecords.length === 0) {
      //   VXETable.modal.message({ content: `新增 ${insertRecords.length} 条，更新 ${updateRecords.length} 条`, status: 'warning' })
      //   return
      // }
      if(tableData.length == 0 ){
        VXETable.modal.message({ content: ` 表格数据 ${insertRecords.length} 条`,  status: 'warning' })
           return
      }
      // 修改时 是否已审核
      // console.log(tableData, ' tableData')
      if (tableData.length > 0) {
        const isFstatus = tableData.filter(it => Number(it.fstatus4) === 1)
        if (isFstatus.length) {
          this.$message({
            message: '已审核，不能修改！',
            type: 'error'
          })
          return
        }
      }

      // console.log(updateRecords, ' updateRecords')
      // console.log(removeRecords, ' removeRecords')
      // console.log(tableData, ' tableData')
      // console.log(insertRecords, removeRecords, updateRecords, insertRecords.length > 0, updateRecords.length > 0, removeRecords.length > 0)
      console.log(insertRecords, ' insertRecords')
      const insertRecordsArr = []
      if ( insertRecords.length >0){
        insertRecords.map(it => {
          if (it.fbeijianname && it.fbeijiancode && it.fbeijianhao) {
            insertRecordsArr.push(it)
          }
        })
      }
     

      const tableDataArr = []
      tableData.map(it => {
        if (it.fbeijianname && it.fbeijiancode && it.fbeijianhao) {
          tableDataArr.push(it)
        }
      })

 

      // return
      try {
        // const res = await beijianSave({ FRepKey, opername: this.opername, insertRecords, updateRecords, removeRecords, tableData, formdata: this.formData })
        const res = await beijianSave({ FRepKey, opername: this.opername, insertRecords: insertRecordsArr, updateRecords, removeRecords, tableData: tableDataArr, formdata: this.formData })
        if (res.Error === 0) {
          this.$message({
            message: res.Message,
            type: 'success'
          })
        } else {
          this.$message({
            message: res.Message,
            type: 'error'
          })
        }
        // this.getvxetableGenList()
      } catch (error) {
        console.log(error)
      }

      // VXETable.modal.message({ content: `新增 ${insertRecords.length} 条，更新 ${updateRecords.length} 条`, status: 'success' })
    },

    // 删除
    async vxeDel() {
      console.log(11111)
      const $grid = this.$refs.xGrid

      // 删除当前行    VXETable.modal.alert($grid.getCurrentRecord())
      $grid.remove($grid.getCurrentRecord())

      // if ($grid.getCheckboxRecords().length === 0) {
      //   VXETable.modal.message({ content: `请选中一行`, status: 'warning' })
      //   return
      // }

      // 判断已审核
      // const dataTemp = $grid.getCheckboxRecords()
      // const isFstatus = dataTemp.filter(it => Number(it.fstatus) === 1)
      // if (isFstatus.length) {
      //   this.$message({
      //     message: '已审核，不能删除！',
      //     type: 'error'
      //   })
      //   return
      // }

      // const { removeRecords } = $grid.getRecordset()

      // const res = await vxetableGenAdd({ FRepKey, opername: this.opername, removeRecords })
      // if (res.Error === 0) {
      //   VXETable.modal.message({ content: ` 删除 ${removeRecords.length} 条`, status: 'success' })
      //   this.getvxetableGenList()
      // }
    },

    // 1—审核，0—反审
    async check(Fstatus) {
      const $grid = this.$refs.xGrid
      if ($grid.getCheckboxRecords().length === 0) {
        VXETable.modal.message({ content: `请选中一行`, status: 'warning' })
        return
      }
      const checkData = []
      $grid.getCheckboxRecords().map(it => {
        checkData.push(it.fid)
      })

      if (Number(Fstatus) === 1) {
        this.$confirm('是否审核, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          cancelButtonClass: 'btn-custom-cancel',
          type: 'warning'
        }).then(async() => {
          try {
            const res = await checkStatus({
              db: this.globalDb.db,
              opername: decodeURIComponent(this.globalDb.fname),
              loginname: decodeURIComponent(this.globalDb.fname),
              FRepKey,
              Fstatus, // 1—审核，0—反审
              fid: checkData.join(',')

            })
            if (res.Error === 0) {
              this.$message({
                message: res.Message,
                type: 'success'
              })
              await this.getvxetableGenList()
            } else {
              this.loadingForm = false
              this.$message({
                message: res.Message,
                type: 'error'
              })
            }
          } catch (error) {
            console.log(error)
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
      } else {
        try {
          const res = await checkStatus({
            db: this.globalDb.db,
            opername: decodeURIComponent(this.globalDb.fname),
            loginname: decodeURIComponent(this.globalDb.fname),
            FRepKey,
            Fstatus, // 1—审核，0—反审
            fid: checkData.join(','),
            appname: ''
          })
          if (res.Error === 0) {
            this.$message({
              message: res.Message,
              type: 'success'
            })
            await this.getvxetableGenList()
          } else {
            this.loadingForm = false
            this.$message({
              message: res.Message,
              type: 'error'
            })
          }
        } catch (error) {
          console.log(error)
        }
      }
    },

    // 内容列表
    async getvxetableGenList() {
      const param = { opername: decodeURIComponent(this.globalDb.fname), FRepKey, keyword: this.keyword, isHebing: this.isHebing, fstatus: this.fstatus, page: this.tablePage.currentPage, pageSize: this.tablePage.pageSize }
      const res = await XsbList(param)
      setTimeout(() => {
        this.tablePage.total = res.total
        this.gridOptions.data = res.Data
        // res.Data
      }, 0)
    },
    // 编辑内容设置
    async getBeijianEdit() {
      const param = { FRepKey, fbillno, db: this.globalDb.db }
      const res = await beijianEdit(param)
      setTimeout(() => {
        // const $grid = this.$refs.xGrid
        // for (let i = 0; i < res.Data.length; i++) {
        //   $grid.insert(res.Data[i], -1)
        // }
        if (res.Data && res.Data.length) {
          this.gridOptions.data = res.Data
          this.$set(this.formData, 'fbillno', res.Data[0].fbillno)
          this.$set(this.formData, 'fchuanmin', res.Data[0].fchuanmin)
          this.$set(this.formData, 'fchuanhao', res.Data[0].fchuanhao)
          this.$set(this.formData, 'fmodel', res.Data[0].fmodel)
          this.$set(this.formData, 'fprodectno', res.Data[0].fprodectno)
          this.$set(this.formData, 'fcustomer', res.Data[0].fcustomer)
          this.$set(this.formData, 'fzhibaoqi', res.Data[0].fzhibaoqi)
          // console.log(res.Data, ' res.Data')
          // this.fqtykc = res.Data[0].fqtykc
        }
      }, 0)
    },
    // 分页
    handlePageChange({ currentPage, pageSize }) {
      this.tablePage.currentPage = currentPage
      this.tablePage.pageSize = pageSize
      this.getvxetableGenList()
    },

    addressClickEvent(row) {
      VXETable.modal.alert(`address点击事件：${row.address}`)
    },

    // 按钮点击
    async toolbarButtonClickEvent({ code }) {
      console.log(code, 'code toolbarButtonClickEvent')
      const $grid = this.$refs.xGrid
      switch (code) {
        case 'myInsert':
          console.log(234, $grid)
          $grid.insert({

          })
          break
        // 保存
        case 'mySave':
          setTimeout(async() => {
            const { insertRecords, removeRecords, updateRecords } = $grid.getRecordset()

            if (insertRecords.length === 0 && updateRecords.length === 0 && removeRecords.length === 0) {
              VXETable.modal.message({ content: `新增 ${insertRecords.length} 条，更新 ${updateRecords.length} 条`, status: 'warning' })
              return
            }
            console.log(insertRecords, removeRecords, updateRecords, insertRecords.length > 0, updateRecords.length > 0, removeRecords.length > 0)
            try {
              const res = await vxetableGenAdd({ FRepKey, opername: this.opername, insertRecords, updateRecords, removeRecords })
              if (res.Error === 200) {
                this.getvxetableGenList()
                VXETable.modal.message({ content: `新增 ${insertRecords.length} 条，更新 ${updateRecords.length} 条`, status: 'success' })
              } else {
                VXETable.modal.message({ content: res.Message, status: 'error' })
              }
            } catch (error) {
              console.log(error)
            }
          })
          break
        // 删除
        case 'myDelete':
          if ($grid.getCheckboxRecords().length === 0) {
            VXETable.modal.message({ content: `请选中一行`, status: 'warning' })
            return
          }
          setTimeout(async() => {
            const { removeRecords } = $grid.getRecordset()

            $grid.removeCheckboxRow()
            const res = await vxetableGenAdd({ FRepKey, opername: this.opername, removeRecords })
            if (res.Error === 0) {
              VXETable.modal.message({ content: ` 删除 ${removeRecords.length} 条`, status: 'success' })
              this.getvxetableGenList()
            }

            // $grid.clearSelected()
            // $grid.clearCheckboxRow()
          })
          break

        case 'myInsertTZ':

          break

        case 'myAA':
          VXETable.modal.message({ content: '新增', status: 'success' })
          break
      }
    },

    sumNum(list, field) { // DONE
      let count = 0
      list.forEach(item => {
        count += Number(item[field]) * 100
      })
      return (count / 100)
    },

    formatAmount({ cellValue }) {
      return cellValue ? `￥${XEUtils.commafy(XEUtils.toNumber(cellValue), { digits: 2 })}` : ''
    },
    formatDate({ cellValue }) {
      return XEUtils.toDateString(cellValue, 'yyyy-MM-dd HH:ss:mm')
    },
    checkColumnMethod({ column }) {
      if (['nickname', 'role'].includes(column.property)) {
        return false
      }
      return true
    }

  }

}

</script>

